import axios from 'axios'
import store from '@/store'
// import { Message } from 'view-design'
// import { Message } from 'iview'
import {
    Message, Modal
} from 'view-design'
import { removeToken } from "@/libs/util";
import router from "@/router";

//地址
// let base = 'http://192.168.0.106:8091'
let base = 'http://192.168.1.100:8091'
// let base = ''
export {
    base
}

axios.interceptors.request.use(
    function (config) {
        // console.log('config', config);
        let token = store.state.user.token
        // if (token && config.isToken) {
        console.log(config);
        config.headers.login_source = 'xc_pc'
        config.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`
        //config.headers.common['token'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IuWRqOaYjOS4viIsImV4cCI6MTY4MTg4NTAzMSwidXNlcklkIjoiMTAifQ.XN01fJ7ox9-xNEFqVzHPXuHtlog-HDJM43PqQ3_aNcM'
        // }
        if (store.state.user.flag === 'token') {
            config.headers.token = localStorage.getItem('token')
        }
        // if (token&&config.url !== '/login') { config.headers.token = `Bearer ${localStorage.getItem('token')}`; }
        return config
    },
    function (error) {
        // store.commit('setHTTPLoading', false)
        return Promise.reject(error)
    }
)
// 响应拦截器
const whiteList = ['/', 'login', 'register', 'findpassword']  // 白名单内 不验证登录超时
axios.interceptors.response.use(res => {
    console.log(res);
    const code = res.data.code;
    console.log(code);
    const msg = res.data.message || res.data.msg;
    // if (!whiteList.includes(router.currentRoute.name) && code == 10001) {
    //     Modal.confirm({
    //         title: '系统提示',
    //         content: "登录超时，请重新登录",
    //         okText: '重新登录',
    //         onOk: () => {
    //             removeToken();
    //             // 清空路由配置并回到登录页面
    //             localStorage.clear();
    //             router.push({
    //                 name: "login",
    //             });
    //         },
    //     })
    //     return Promise.reject(msg)
    // } else if (code == 10002) {
    //     Message.error(msg);
    //     return Promise.reject(new Error(msg))
    // } else if (code == 500) {
    //     Message.error(msg);
    //     return Promise.reject(new Error(msg))
    // } else {
    //     return res
    // }
    return res.data
},
    error => {
        console.log(error);
        // console.log(document.cookie);
        // console.log(localStorage.myData);
        const code = error.response.data.code;
        console.log(code);
        // if (!whiteList.includes(router.currentRoute.name) && code == 10001) {
        //     Modal.confirm({
        //         title: '系统提示',
        //         content: "登录超时，请重新登录",
        //         okText: '重新登录',
        //         onOk: () => {
        //             removeToken();
        //             // 清空路由配置并回到登录页面
        //             localStorage.clear();
        //             router.push({
        //                 name: "login",
        //             });
        //         },
        //     })
        // }
        return Promise.reject(error)
    }
)

const addErrorLog = errorInfo => {
    const {
        statusText,
        status,
        request: {
            responseURL
        }
    } = errorInfo
    let info = {
        type: 'ajax',
        code: status,
        mes: statusText,
        url: responseURL
    }
    // if (!responseURL.includes('save_error_logger')) {
    //   store.dispatch('addErrorLog', info)
    // }
}

class HttpRequest {
    constructor(baseUrl = this.$config.baseURL) {
        this.baseUrl = baseUrl
        this.queue = {}
    }

    getInsideConfig () {
        const config = {
            baseURL: this.baseUrl,
            // baseURL: '',
            headers: {
                //
            }
        }
        return config
    }

    destroy (url) {
        delete this.queue[url]
        if (!Object.keys(this.queue).length) {
            // Spin.hide()
        }
    }

    interceptors (instance, url) {
        // 请求拦截
        instance.interceptors.request.use(
            config => {
                // K1Xcuk0nesWvC0nQf8RX16aN6DdGZSRKOuY1HQAoBTg=
                // config.headers.common['token'] = 'K1Xcuk0nesWvC0nQf8RX16aN6DdGZSRKOuY1HQAoBTg='
                // 添加全局的loading...
                if (!Object.keys(this.queue).length) {
                    // Spin.show() // 不建议开启，因为界面不友好
                }
                this.queue[url] = true
                return config
            },
            error => {
                return Promise.reject(error)
            }
        )
        // 响应拦截
        instance.interceptors.response.use(
            res => {
                this.destroy(url)
                const {
                    data,
                    status
                } = res
                return {
                    data,
                    status
                }
            },
            error => {
                this.destroy(url)
                let errorInfo = error.response
                if (!errorInfo) {
                    const {
                        request: {
                            statusText,
                            status
                        },
                        config
                    } = JSON.parse(JSON.stringify(error))
                    errorInfo = {
                        statusText,
                        status,
                        request: {
                            responseURL: config.url
                        }
                    }
                }
                addErrorLog(errorInfo)
                return Promise.reject(error)
            }
        )
    }

    request (options) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

export const getRequest = (_url, params = {}, isToken = true) => {
    return new Promise((resolve, reject) => {
        axios
            .request({
                url: `${base}${_url}`,
                method: 'get',
                params,
                isToken,
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
                // if (err.response.data.code !== "10001") {  // 非token认证失败时提示
                //     Message.error(err.message)
                // }
            })
    })
}

export const postRequest = (_url, params = {}, isToken = true) => {
    const CancelToken = axios.CancelToken;
    window.cancle = null;
    return new Promise((resolve, reject) => {
        axios
            .request({
                url: `${base}${_url}`,
                // url: `${_url}`,
                method: 'post',
                data: params,
                isToken,
                transformRequest: [
                    function (data) {
                        return JSON.stringify(data)
                    }
                ],
                headers: {
                    'Content-Type': 'application/json'
                },
                cancelToken: new CancelToken(function executor (c) {  //在axios封装的函数中写上这句就可以了
                    window.cancle = c;
                })
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
                // if (err.response.data.code !== "10001") {  // 非token认证失败时提示
                //     Message.error(err.message)
                // }
            })
    })
}

export function deleteRequest (_url, params) {
    return new Promise((resolve, reject) => {
        let url = `${base}${_url}`
        axios
            .delete(url, params)
            .then(res => {
                if (res.status === 'ERROR') {
                    Message.error(res.msg)
                } else {
                    resolve(res.data)
                }
            })
            .catch(err => {
                reject(err.data)
            })
    })
}

export const exportdedicated = (_url, params = {}, isToken = true) => {
    return new Promise((resolve, reject) => {
        axios
            .request({
                headers: {
                    "Content-Type": "application/json",
                    // "token":JSON.parse(window.localStorage.getItem("myData")).token
                    "token": 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IuWRqOaYjOS4viIsImV4cCI6MTY4MTU0OTcwMCwidXNlcklkIjoiMTAifQ.WyjDjT1vYgtTyW1S6WsdrLocUaZm1XkDgFztqC9x_XY.eyJ1c2VyTmFtZSI6IumDneS4veiKsyIsImV4cCI6MTY2NzYxMzU1NiwidXNlcklkIjoiOCJ9.IdOQRsW8cVHYysQFzLnF9VUrj5gwO-lv4v92AXMT0n4'
                },
                url: `${base}${_url}`,
                data: params,
                responseType: "blob",
                method: 'post',
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
                if (err.response.data.code !== "10001") {  // 非token认证失败时提示
                    Message.error(err.message)
                }
            })
    })
}
export default HttpRequest
